import { APIResponse, APIResult } from '@/request'

type Options<T = any> = {
  currentKey?: string
  pageSizeKey?: string
  totalKey?: string
  formatRes?: Func<[APIResponse<T>], any>
}

export const usePagination = <T = any>(requestFunc: Func, options: Options) => {
  const { currentKey = 'current', pageSizeKey = 'pageSize', totalKey = 'total', formatRes } = options

  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
  })
  const data = ref<T>()
  const loading = ref(false)

  const handleResponse = (res: APIResponse<T>) => {
    data.value = formatRes ? formatRes(res) : res.data?.pageData
  }

  const handlePagination = (res: APIResponse<T>) => {
    pagination.total = res.data?.[totalKey] || 0
  }

  const run = async (params?: any) => {
    loading.value = true
    let res: any
    try {
      res = await requestFunc(params)
    } finally {
      loading.value = false
    }

    handlePagination(res)

    return handleResponse(res)
  }

  return {
    loading,
    data,
    pagination,
    run,
  }
}
